package com.fbt.transfer.app.driver.baidu;

import android.util.Log;
import com.baidu.location.BDLocation;
import com.fbt.transfer.app.driver.MyApplication;
import com.fbt.transfer.app.driver.http.AbstractCallback;
import com.fbt.transfer.app.driver.http.ApiClient;
import com.fbt.transfer.app.driver.http.ApiInterface;
import com.fbt.transfer.app.driver.util.LogUtils;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 将位置信息进行上传
 */
public class UpLocationAsyncTask {

  private static volatile LocalDateTime lastTime;
  private static ExecutorService executorService = Executors.newSingleThreadExecutor();
  private static ApiInterface apiInterface;


  public static void execute(BDLocation location) {
    executorService.execute(
        () -> {
          try {
            doInBackground(location);
          } catch (Exception exception) {
            LogUtils.w("GPS_UPLOAD", "上传位置失败");
          }
        });
  }

  private static String doInBackground(BDLocation location) {
    synchronized (UpLocationAsyncTask.class) {
      if(apiInterface==null){
        apiInterface = ApiClient.getApiInterface();
      }
      LocalDateTime currentTime = LocalDateTime.now();
      if (lastTime != null && lastTime.until(currentTime, ChronoUnit.SECONDS) < 3) {
        return "上传频率过快";
      }
      lastTime = currentTime;
    }
    Map<String, Object> hashMap = new HashMap<>(4);
    hashMap.put("latitude", location.getLatitude());
    hashMap.put("longitude", location.getLongitude());
    hashMap.put("angle", location.getDirection());
    hashMap.put("speed", location.getSpeed());
    apiInterface
        .upLocation(hashMap)
        .enqueue(
            new AbstractCallback<Boolean>(
                MyApplication.getApplication().getApplicationContext(), false, false) {
              @Override
              protected void onSuccess(Boolean result) {
                Log.i(
                    "uploadLocation",
                    String.format(
                        "成功上传当前司机位置，纬度:%s,经度:%s,方向:%s,速度:%s",
                        location.getLatitude(),
                        location.getLongitude(),
                        location.getDirection(),
                        location.getSpeed()));
              }
            });
    return "上传成功";
  }
}
